package com.sqlcheck.service.impl;

import com.sqlcheck.model.SqlStatement;
import com.sqlcheck.service.SqlParsingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

@Slf4j
@Service
public class SqlParsingServiceImpl implements SqlParsingService {

    private static final Pattern SQL_DELIMITER_PATTERN = Pattern.compile(";\\s*(?=(?:[^']*'[^']*')*[^']*$)");

    @Override
    public List<SqlStatement> parseUserSql(String sqlContent) {
        List<SqlStatement> statements = new ArrayList<>();

        if (sqlContent == null || sqlContent.trim().isEmpty()) {
            return statements;
        }

        try {
            // 按分号分割SQL语句（考虑字符串内的分号）
            String[] sqlArray = SQL_DELIMITER_PATTERN.split(sqlContent);

            int lineNumber = 1;
            for (int i = 0; i < sqlArray.length; i++) {
                String sql = sqlArray[i].trim();
                if (!sql.isEmpty()) {
                    SqlStatement statement = SqlStatement.builder()
                            .content(sql)
                            .lineNumber(lineNumber)
                            .sqlType(determineSqlType(sql))
                            .sourceType(SqlStatement.SourceType.MANUAL_INPUT)
                            .build();

                    statements.add(statement);

                    // 计算行号（简单估算）
                    lineNumber += countLines(sql);
                }
            }

            log.debug("解析SQL完成，共解析到 {} 条语句", statements.size());

        } catch (Exception e) {
            log.error("解析SQL失败", e);
            throw new RuntimeException("SQL解析失败: " + e.getMessage());
        }

        return statements;
    }

    private SqlStatement.SqlType determineSqlType(String sql) {
        String upperSql = sql.toUpperCase().trim();

        if (upperSql.startsWith("SELECT")) {
            return SqlStatement.SqlType.QUERY;
        } else if (upperSql.startsWith("INSERT") || upperSql.startsWith("UPDATE") || upperSql.startsWith("DELETE")) {
            return SqlStatement.SqlType.DML;
        } else if (upperSql.startsWith("CREATE") || upperSql.startsWith("ALTER") || upperSql.startsWith("DROP")) {
            return SqlStatement.SqlType.DDL;
        } else if (upperSql.contains("PROCEDURE")) {
            return SqlStatement.SqlType.PROCEDURE;
        } else if (upperSql.contains("FUNCTION")) {
            return SqlStatement.SqlType.FUNCTION;
        } else if (upperSql.contains("TRIGGER")) {
            return SqlStatement.SqlType.TRIGGER;
        }

        return SqlStatement.SqlType.QUERY; // 默认为查询
    }

    private int countLines(String text) {
        if (text == null || text.isEmpty()) {
            return 1;
        }
        return (int) text.chars().filter(ch -> ch == '\n').count() + 1;
    }
}